<template>
  <app-page :customNav="true" :login="false">
    <mxp-navbar
      title=""
      homePath="/pages/tab-bar/index1/index1"
      :borderColor="false"
      leftIconColor="#ffffff"
      titleWidth="0px"
      :placeholder="false"
      background="transparent"
    >
      <template #left>
        <text style="width: 480rpx; overflow: hidden; font-size: 15px; color: #ffffff; text-overflow: ellipsis; white-space: nowrap">
          {{ dramaTitle || '短剧' }}
        </text>
      </template>
    </mxp-navbar>
    <template v-if="pageLoadState">
      <view class="page-container" :style="{ width: '100vw', height: `${swiperHeight}px` }">
        <ks-playlet
          :playletId="thirdDramaId!"
          :innerStyle="`width: 750rpx; height: ${swiperHeight}px; background: #000000`"
          :episodeIdList="episodeIdList"
          :showBottomSafeArea="false"
          objectFit="cover"
          :showShare="false"
          :playId="playId!"
          :extParams="{ freeList: freeEpisodeList, payedList: payEpisodeList }"
          :nopermissionplayCallBack="onNopermissionplay"
          :changeCallBack="playletEpisodeChange"
          :playCallBack="onPlay"
        ></ks-playlet>
        <!-- 运营 -->
        <album-operation
          :dramaCover="dramaCover"
          :isChasing="isChasing"
          :safeAreaInsetsBottom="`${safeAreaInsetsBottom + 36 + 100}px`"
          @chasingClick="changeChasingDrama()"
          @introClick="openIntroPopup"
        ></album-operation>
        <!-- 解锁 -->
        <unlock-module
          v-if="!playPermissionStatus"
          :currEpisodeIndex="currEpisodeIndex"
          :title="dramaTitle"
          :loading="data.unlockLoading"
          pointerEvents="none"
          @unlock="() => unlockDrama(currThirdEpisodeId!)"
        ></unlock-module>
      </view>
      <!-- 选集 -->
      <album-title-select
        :serialNo="currEpisodeIndex + 1"
        :totalSeqNum="seqNum"
        :bottom="titleBarBottom"
        :pointerEvents="true"
        :dramaTitle="dramaTitle"
        @openIntroClick="openIntroPopup"
      ></album-title-select>
    </template>
    <mxp-refresh-page v-else ref="mxpRefreshPageRef" :queryData="queryData"></mxp-refresh-page>
    <ad-unlock-popup1 ref="adUnlockPopup1Ref"></ad-unlock-popup1>
    <ad-unlock-popup2 ref="adUnlockPopup2Ref"></ad-unlock-popup2>
    <intro-popup ref="introPopupRef" :isThird="true" :thirdDramaId="thirdDramaId!" :currEpisodeIndex="currEpisodeIndex" :height="popupHeight"></intro-popup>
    <pay-popup ref="payPopupRef" :currEpisodeIndex="currEpisodeIndex" :thirdDramaId="thirdDramaId!"></pay-popup>
  </app-page>
</template>

<script setup lang="ts">
  import { onLoad, onReady, onShareAppMessage, onUnload } from '@dcloudio/uni-app';
  import { computed, reactive, ref } from 'vue';
  import AppPage from '@/components/app-page/app-page.vue';
  import PayPopup from './components/pay-popup.vue';
  import IntroPopup from '@/components/page/intro-popup/intro-popup.vue';
  import AdUnlockPopup1 from '@/components/pay/ad-unlock-popup1/ad-unlock-popup1.vue';
  import AdUnlockPopup2 from '@/components/pay/ad-unlock-popup2/ad-unlock-popup2.vue';
  import MxpNavbar from '@/mxp-ui/mxp-navbar/mxp-navbar.vue';
  import UnlockModule from '@/components/page/unlock-module/unlock-module.vue';
  import { addChasingDramaAxios, addWatchDramaAxios, cancelChasingDramaAxios, initKsDramaPlayInfoAxios } from '@/api/drama';
  import useMxpToastRefHooks from '@/utils/hooks/useToast';
  import type { PlayletOnChangeEvent, PlayletOnNopermissionplayEvent } from 'mxp-uni-types';
  import { addAdRecordAxios, createKsAdvertOrderAxios, createKsBalanceOrderAxios } from '@/api/pay';
  import { autoLogin } from '@/utils/page/user';
  import { useBaseInfo } from './util';
  import { RewardedVideoAd } from '@/utils/page/adUtil';
  import AlbumTitleSelect from '@/components/page/album-title-select/album-title-select.vue';
  import { getAppInfo } from '@/config/mp-config';
  import { sleep } from '@/mxp-ui/mxp-tool/utils/rest';
  import AlbumOperation from '@/components/page/album-operation/album-operation.vue';
  import mxpGetSysInfoStore from '@/mxp-ui/mxp-tool/store/mxp-store-sys-info';
  import type { KsMpConfig } from '@/config/mp/ks';
  import MxpRefreshPage, { type Ins } from '@/mxp-ui/mxp-refresh-page/mxp-refresh-page.vue';
  import { useRefresh } from '@/mxp-ui/mxp-tool/hooks/useHooksRefresh.ts';

  const { mxpRefreshPageRef } = useRefresh();
  const mxpToastRef = useMxpToastRefHooks();

  const {
    /** 自动解锁 */
    isAutoPay,
    /** appStore */
    appStore,
    /** 登录状态 */
    loginState,
    /** 底部标题栏的 Bottom 偏移 */
    popupHeight,
    /** 底部标题栏的 Bottom 偏移 */
    titleBarBottom,
    /** swiper高度 */
    swiperHeight,
  } = useBaseInfo();

  const data = reactive({
    /** 是否正在解锁 */
    unlockLoading: false,
    /** 底部标题栏的透明度 */
    titleBarOpacity: 1,
    /** 底部标题栏的PointerEvents */
    titleBarPointerEvents: 'auto' as 'auto' | 'none',
  });
  const sys = mxpGetSysInfoStore().getSysInfo();
  /** 底部安全距离 */
  const safeAreaInsetsBottom = computed(() => sys.value.safeAreaInsets?.bottom || 0);
  /** 页面加载状态 */
  const pageLoadState = ref(false);
  /** 第三方的短剧 ID */
  const thirdDramaId = ref<string | undefined>(undefined);
  /** 当前第三方的剧集ID */
  const currThirdEpisodeId = ref<string | undefined>(undefined);
  // 快手专用的解决直接用currThirdEpisodeId导致滑动是的问题（仅在初始赋值，后续不去改变他）
  const playId = ref<number | string | undefined>(undefined);
  /** 是否追剧 */
  const isChasing = ref<0 | 1>(0);
  /** 标题 */
  const dramaTitle = ref('');
  /** 短剧封面 */
  const dramaCover = ref('');
  /** 总集数 */
  const seqNum = ref(0);
  /** 免费集数 (主要用于快手) */
  const freeEpisodeList = ref<number[]>([]);
  /** 已支付集数  (主要用于快手)  */
  const payEpisodeList = ref<number[]>([]);
  /** 所有的剧集ID  (主要用于快手)  */
  const episodeIdList = ref<string[]>([]);
  /** 当前剧集的下标 */
  const currEpisodeIndex = ref(-1);
  /** 是否有权播放 */
  const playPermissionStatus = ref(false);
  /** 追剧请求状态 */
  const chasingLoading = ref(false);

  const adUnlockPopup1Ref = ref<InstanceType<typeof AdUnlockPopup1>>();
  const adUnlockPopup2Ref = ref<InstanceType<typeof AdUnlockPopup2>>();
  const payPopupRef = ref<InstanceType<typeof PayPopup> | null>(null);
  const introPopupRef = ref<InstanceType<typeof IntroPopup> | null>(null);

  let rewardedVideoAd: RewardedVideoAd | undefined = undefined;

  onShareAppMessage(() => {
    let url = `/pages/drama/playlet-ks/playlet-ks`;
    url += `?ksPlayletId=${thirdDramaId.value}&ksEpisodeId=${currThirdEpisodeId.value}&ksSeq=${currEpisodeIndex.value + 1}`;
    return { imageUrl: dramaCover.value, title: `${dramaTitle.value}(${`第${currEpisodeIndex.value + 1}集`})`, path: url };
  });

  onLoad((param) => {
    thirdDramaId.value = param?.ksPlayletId || undefined;
    currThirdEpisodeId.value = param?.ksEpisodeId || undefined;
    playId.value = currThirdEpisodeId.value;
  });

  onReady(() => {
    rewardedVideoAd = useAd();
  });
  onUnload(() => {
    rewardedVideoAd?.destroy();
  });

  /** 播放剧集 */
  function onPlay() {
    loginState && addWatchDramaAxios({ thirdDramaId: thirdDramaId.value!, episodeSeq: currEpisodeIndex.value + 1 });
  }

  /**
   * 获取数据
   */
  async function queryData(ins: Ins) {
    try {
      pageLoadState.value = false;
      try {
        !appStore.loginState && (await autoLogin());
      } catch (error) {
        console.log('自动登录错误====', error);
      }
      const res = await initKsDramaPlayInfoAxios({
        thirdDramaId: thirdDramaId.value!,
        referralLinkId: appStore?.launchQuery?.referralLinkId,
        channelId: appStore.launchQuery?.channelId || undefined,
        clickid: appStore.launchQuery?.clickid || undefined,
        projectId: appStore.launchQuery.projectid || undefined,
        promotionId: appStore.launchQuery.promotionid || undefined,
        launchQuery: JSON.stringify(appStore?.launchQuery || {}),
      });

      appStore.updateIsIaaFlag(res.data.isIaaFlag);
      episodeIdList.value = res.data.episodeIdList || [];
      dramaCover.value = res.data.dramaCover;
      dramaTitle.value = res.data.dramaTitle || '';
      freeEpisodeList.value = res.data.freeEpisodeList || [];
      payEpisodeList.value = res.data.payEpisodeList || [];
      isChasing.value = res.data.isChasing || 0;
      seqNum.value = res.data.seqNum || 0;
      thirdDramaId.value = res.data.thirdDramaId || thirdDramaId.value;
      playId.value = currThirdEpisodeId.value;

      const _currEpisodeIndex = episodeIdList.value.findIndex((item) => item === currThirdEpisodeId.value);
      if (_currEpisodeIndex < 0) {
        currThirdEpisodeId.value = episodeIdList.value[0];
        currEpisodeIndex.value = 0;
      } else {
        currEpisodeIndex.value = _currEpisodeIndex;
      }
      const eqs = currEpisodeIndex.value + 1;
      playPermissionStatus.value = [...freeEpisodeList.value, ...payEpisodeList.value].findIndex((item) => item === eqs) >= 0;
      pageLoadState.value = true;
      ins.setSuccess();
    } catch (error) {
      pageLoadState.value = false;
      ins.setEmpty('fail_load', error.msg || '获取数据失败，BD001');
    }
  }

  /** 监听快手剧集切换事件 (快手专用) */
  function playletEpisodeChange(event: PlayletOnChangeEvent) {
    const ksPlayId = event.detail.episodeId;
    currEpisodeIndex.value = episodeIdList.value.findIndex((item) => item === ksPlayId);
    currThirdEpisodeId.value = ksPlayId;
    const eqs = currEpisodeIndex.value + 1;
    playPermissionStatus.value = [...freeEpisodeList.value, ...payEpisodeList.value].findIndex((item) => item === eqs) >= 0;
  }

  /**
   * 无权限播放
   */
  function onNopermissionplay(event: PlayletOnNopermissionplayEvent) {
    playPermissionStatus.value = false;
    unlockDrama(event.episodeId);
  }

  /** 追剧 */
  async function changeChasingDrama() {
    try {
      !loginState.value && (await autoLogin());
      chasingLoading.value = true;
      if (isChasing.value === 1) {
        await cancelChasingDramaAxios({ thirdDramaId: thirdDramaId.value! });
      } else {
        await addChasingDramaAxios({ thirdDramaId: thirdDramaId.value! });
      }
      isChasing.value = isChasing.value === 1 ? 0 : 1;
      chasingLoading.value = false;
    } catch (error) {
      chasingLoading.value = false;
      uni.showToast({ title: error.msg || '操作失败,BD001', icon: 'none', position: 'bottom' });
    }
  }

  /** 显示简介弹出框 */
  function openIntroPopup() {
    introPopupRef.value?.show({
      cutEpisode(index: number) {
        if (currEpisodeIndex.value !== index) {
          currEpisodeIndex.value = index;
          currThirdEpisodeId.value = episodeIdList.value[index];
          playId.value = currThirdEpisodeId.value;
        }
      },
    });
  }

  /**
   * 解锁剧集
   */
  async function unlockDrama(_thirdEpisodeId: string) {
    try {
      !loginState.value && (await autoLogin());
      if (isAutoPay.value) {
        await setDiamondUnlock(_thirdEpisodeId);
      } else {
        openPopup(_thirdEpisodeId);
      }
    } catch (error) {
      console.log('error====', error);
    }
  }

  /**
   * 通过是否为 AII 判断 显示广告解锁弹出框,还是支付弹出框
   */
  function openPopup(_thirdEpisodeId: string) {
    appStore.isIaaFlag === 1 ? openAd1Popup(_thirdEpisodeId) : openPayPopup(_thirdEpisodeId);
  }

  /** 注册广告 */
  function useAd() {
    const appinfo = getAppInfo() as KsMpConfig | undefined;
    const ksAdType = appinfo?.ksAdType || -1;
    const ksAdUnitId = appinfo?.ksAdUnitId || -1;

    return new RewardedVideoAd({
      ksAdType,
      ksAdUnitId,
      /** 广告关闭回调 */
      adCloseCallback: async (_data) => {
        uni.showLoading({ mask: true, title: '解锁中...' });
        if (_data.isEnded) {
          try {
            await sleep(10);
            const recordRes = await addAdRecordAxios({
              thirdDramaId: thirdDramaId.value!,
              episodeSeq: currEpisodeIndex.value + 1,
              referralLinkId: appStore.launchQuery?.referralLinkId,
              promotionId: appStore.launchQuery?.promotionid,
              launchQueryPramas: appStore.newLaunchQuery || {},
            });
            const param = { advertToken: recordRes.data.advertToken, thirdDramaId: thirdDramaId.value!, episodeSeq: currEpisodeIndex.value + 1 };
            const unlockOrderRes = await createKsAdvertOrderAxios(param);
            payEpisodeList.value = unlockOrderRes.data.payEpisodeList;
            playPermissionStatus.value = true;
            uni.hideLoading();
            uni.showToast({ title: '解锁成功', icon: 'none', position: 'bottom' });
          } catch (error) {
            uni.hideLoading();
            uni.showToast({ title: '广告解锁失败,-0003', icon: 'none', position: 'bottom' });
          }
        } else {
          uni.hideLoading();
          console.log('未观看完视频');
          openAd2Popup();
        }
      },
    });
  }

  /**
   * 广告解锁
   */
  async function handleAd() {
    const ad = rewardedVideoAd?.getAdInstance();
    if (ad) {
      try {
        uni.showLoading({ mask: true, title: '广告加载中...' });
        await ad.show();
        uni.hideLoading();
      } catch (error) {
        // 失败一次重试
        try {
          await ad.load();
          await ad?.show();
          uni.hideLoading();
        } catch (error2) {
          uni.hideLoading();
          console.log('error====', error2);
          uni.showToast({ title: '广告加载失败，BD001', icon: 'none', position: 'bottom' });
        }
      }
    } else {
      uni.showToast({ title: '广告加载失败，BD002', icon: 'none', position: 'bottom' });
    }
  }

  /** K币解锁 (当前或下一集) */
  async function setDiamondUnlock(_thirdEpisodeId: string) {
    try {
      data.unlockLoading = true;
      const res = await createKsBalanceOrderAxios({
        thirdDramaId: thirdDramaId.value!,
        episodeSeq: currEpisodeIndex.value + 1,
        referralLinkId: appStore.launchQuery?.referralLinkId,
      });
      if (res.data.unLockStatus === 1) {
        appStore.updateVirtualCoins(res.data.virtualCoins);
        payEpisodeList.value = res.data.payEpisodeList;
        playPermissionStatus.value = true;
        data.unlockLoading = false;
        mxpToastRef.value?.showSuccess('解锁成功');
        return Promise.resolve(true);
      } else {
        data.unlockLoading = false;
        openPopup(_thirdEpisodeId);
        return Promise.reject('K币解锁失败,BDZS001');
      }
    } catch (error) {
      data.unlockLoading = false;
      return Promise.reject(error || 'K币解锁失败');
    }
  }

  /** 打开支付弹出框 */
  function openPayPopup(_thirdEpisodeId: string) {
    payPopupRef.value?.show({
      dramaTitle: dramaTitle.value!,
      /** 支付成功 */
      paySuccess(_payEpisodeList: number[]) {
        payEpisodeList.value = _payEpisodeList;
        playPermissionStatus.value = true;
      },
      /** 弹出广告解锁弹出框 */
      adUnlock() {
        openAd1Popup(_thirdEpisodeId);
      },
    });
  }

  /** 打开广告解锁1 弹出框 */
  function openAd1Popup(_thirdEpisodeId: string) {
    adUnlockPopup1Ref.value?.show({
      /** 关闭弹出框 */
      closePopup() {
        openAd2Popup();
      },
      /** 打开广告视频 */
      openAd() {
        handleAd();
      },
      /** 打开充值弹出框 */
      openPay() {
        openPayPopup(_thirdEpisodeId);
      },
    });
  }

  /** 打开广告解锁2 弹出框 */
  function openAd2Popup() {
    adUnlockPopup2Ref.value?.show({
      /** 打开广告视频 */
      openAd() {
        handleAd();
      },
    });
  }
</script>

<style lang="scss">
  page {
    background: #000000;
  }
</style>

<style scoped lang="scss">
  .page-container {
    position: absolute;
    z-index: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .container {
    background-color: #000000;
  }
</style>
